package com.estronger.shopmanage.ui.measure;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B16PlanMeasure;
import com.estronger.shopmanage.bean.B16PlanMeasure.MeasureGoods;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.until.PictureUtil;
import com.estronger.shopmanage.utils.BitmapHelper;
import com.estronger.shopmanage.utils.FileUtil;
import com.estronger.shopmanage.utils.FileUtils;
import com.estronger.shopmanage.view.AbnormalDeclareView;
import com.estronger.shopmanage.view.AddFileView;
import com.estronger.shopmanage.view.AddPhotosView;
import com.estronger.shopmanage.view.bean.BitmapItem;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.soonfor.evaluate.bean.FileUploadBean;
import com.soonfor.evaluate.tools.ImageUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.utils.UiUtils;
import com.estronger.shopmanage.view.AppDialog;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MeasureInputActivity extends BaseActivity implements AddPhotosView.EventListener, AddFileView.EventListener {

    private MeasureInputActivity mActivity;
    private TextView tv_client, tv_actual_time, tv_finish_date,
            tv_conversation_time, tv_title;
    private LinearLayout ll_list_contener, ll_goods_contener, ll_all_contener;
    private String measureid;
    private EditText et_cts_need;

    //整体测量单，整体现场及整改图片选择或拍照
    private AddPhotosView view_all_bill, view_all_place;
    //整体 附件
    private AddFileView view_all_file;
    //去选择图片
    private int CODE_ALL_BILL = 1001, CODE_ALL_PLACE = 2002, CODE_ALL_FILE = 3003;
    //上传完成的标志
    private boolean allBillUploadFn = false, allPlaceUploadFn = false, allFileUploadFn = false;
    private ArrayList<String> allBillPaths = new ArrayList<String>();//已上传成功的整体测量单
    private ArrayList<String> allPlacePaths = new ArrayList<String>();//已上传成功的整体现场及整改图片
    private ArrayList<FileUploadBean> allFileBeans = new ArrayList<>();//已上传成功的整体附件


    private RequestParams saveParams;
    private B16PlanMeasure bean;
    private View rootView;

    private Map<String, LocalMedia> goodsPhotoMap;//所有明细产品的图片集合

    @Override
    protected void init() {
        goodsPhotoMap = new HashMap<>();
        measureid = getIntent().getStringExtra("measureid");
    }

    // 初始化各个View
    @Override
    protected void initView() {
        rootView = View.inflate(this, R.layout.activity_result, null);
        setContentView(rootView);
        this.mActivity = MeasureInputActivity.this;
        tv_client = (TextView) findViewById(R.id.result_item_name_real);
        tv_title = (TextView) findViewById(R.id.measure_title);
        tv_title.setText("测量结果输入");
        tv_actual_time = (TextView) findViewById(R.id.result_time_real);
        tv_finish_date = (TextView) findViewById(R.id.result_finish_date);
        tv_conversation_time = (TextView) findViewById(R.id.conversation_time_real);
        ll_list_contener = (LinearLayout) findViewById(R.id.result_list_contener);
        initAll();
        et_cts_need = (EditText) findViewById(R.id.measure__input_remark);
        ll_goods_contener = (LinearLayout) findViewById(R.id.measure_goods_contener);
        // 获取测量详情
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "getplanmeasure");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("measureid", measureid);
        connect(params, NetManager.CONTENT);
    }


    // 初始化整体测量单各个View
    public void initAll() {
        ll_all_contener = (LinearLayout) findViewById(R.id.result_all);
        view_all_bill = findViewById(R.id.view_all_bill);
        view_all_place = findViewById(R.id.view_all_place);
        view_all_file = findViewById(R.id.view_all_file);
        view_all_bill.initView(mActivity, CODE_ALL_BILL, this);
        view_all_bill.initData("整体测量单拍照", 99);
        view_all_place.initView(mActivity, CODE_ALL_PLACE, this);
        view_all_place.initData("整体现场及整改拍照", 99);
        view_all_file.initView(mActivity, CODE_ALL_FILE, this);
        view_all_file.initData("整体附件上传", mDialog, true);
    }

    // 对时间格式化
    @Override
    protected void initAction() {
        tv_actual_time.setText(TimeUtils.formatTime(System.currentTimeMillis(), ""));
        tv_conversation_time.setText("");
        tv_finish_date.setText("");
    }

    /**
     * 当前activity所有联网成功的回调
     *
     * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
     * @params result 网络请求成功返回的数据
     */
    @Override
    protected void onNetSuccess(int code, String result) {
        if (NetManager.CONTENT == code) {
            super.onNetSuccess(code, result);
            bean = gson.fromJson(result, B16PlanMeasure.class);
            if (bean.success) {
                if (TextUtils.isEmpty(bean.data.buildname)) {
                    tv_client.setText(bean.data.cstname);
                } else {
                    tv_client.setText(bean.data.buildname + "-"
                            + bean.data.cstname);
                }
                initGoodsItem(bean.data.measureitem);
            } else {
                Toast.show(this, bean.msg, 2000);
            }
        }else if (NetManager.RESULT == code) {
            super.onNetSuccess(code, result);
            BeanBase bean = gson.fromJson(result, BeanBase.class);
            if (bean.success) {
                dimssDialog();
                Toast.show(this, bean.msg, 2000);
                setResult(MeasureActivity.REFLESH_DATA);
                finish();// designer.msg
            } else {
                dimssDialog();
                Toast.show(this, bean.msg, 2000);
            }
        }
    }

    /**
     * 当前activity图片和文件长传成功的回调
     *
     * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
     * @params result 网络请求成功返回的数据
     */
    @Override
    protected void onNetIMGSuccess(int code, String result) {
        if (code == CODE_ALL_BILL) view_all_bill.uploadSuccess(code, result);
        else if (code == CODE_ALL_PLACE) view_all_place.uploadSuccess(code, result);
        else if (code == CODE_ALL_FILE) view_all_file.uploadSuccess(code, result);
        else if (code >= INTO_FILE && code < (INTO_FILE + 20)) {
            BeanImage bean = gson.fromJson(result, BeanImage.class);
            // 进入activity时获取的同事信息
            if (bean.error == 0) {
                itemFile.get(code - INTO_FILE).add(bean.filepath);
            }
        } else if (code >= INTO_BILL && code < (INTO_BILL + 20)) {
            BeanImage bean = gson.fromJson(result, BeanImage.class);
            // 进入activity时获取的同事信息
            if (bean.error == 0) {
                itemBill.get(code - INTO_BILL).add(bean.filepath);
            }
        } else if (code >= INTO_PLACE && code < (INTO_PLACE + 20)) {
            BeanImage bean = gson.fromJson(result, BeanImage.class);
            // 进入activity时获取的同事信息
            if (bean.error == 0) {
                itemPlace.get(code - INTO_PLACE).add(bean.filepath);
            }
        }
    }

    /**
     * 当前activity请求网络失败的回调
     *
     * @params code 各个接口返回的唯一识别码，用来判断是哪个接口失败返回
     * @params result 失败信息
     */
    @Override
    protected void onNetErorr(int code, String msg) {
        if (code == CODE_ALL_BILL) view_all_bill.uploadFail(code, msg);
        else if (code == CODE_ALL_PLACE) view_all_place.uploadFail(code, msg);
        else if (code == CODE_ALL_FILE) view_all_file.uploadFail(code, msg);
        else if (code >= INTO_BILL && code < (INTO_BILL + 20)) {
            Log.i("JSON", "INTO_ALL_PLACE fail");
        }else if (code >= INTO_PLACE && code < (INTO_PLACE + 20)) {
            Log.i("JSON", "INTO_ALL_PLACE fail");
        }else if (NetManager.RESULT == code) {
            dimssDialog();
            Toast.show(this, "保存失败", 2000);
        }
    }


    /**
     * 明细产品的相关字段
     */

    private ArrayList<ArrayList<String>> itemBill = new ArrayList<ArrayList<String>>();//上传的图片路径集合-产品的测量单
    private ArrayList<ArrayList<String>> itemPlace = new ArrayList<ArrayList<String>>();//上传的图片路径集合-产品的现场及整改图片
    private ArrayList<ArrayList<String>> itemFile = new ArrayList<ArrayList<String>>();//上传的图片路径集合-产品的附件
    private TextView goods_name, goods_count, goods_property, goods_feature;
    private ImageView goods_img, bill_select_bt, bill_camera_bt,
            place_select_bt, place_camera_bt, fill_bt;

    // 填充每一个货物item，并添加进货物容器里面
    private void initGoodsItem(ArrayList<B16PlanMeasure.MeasureGoods> measureitem) {
        View v;
        for (int i = 0; i < measureitem.size(); i++) {
            itemBill.add(new ArrayList<String>());
            itemPlace.add(new ArrayList<String>());
            itemFile.add(new ArrayList<String>());
            MeasureGoods data = measureitem.get(i);
            v = View.inflate(this, R.layout.result_content_goods, null);
            goods_name = (TextView) v.findViewById(R.id.goods_name);
            goods_count = (TextView) v.findViewById(R.id.goods_count);
            goods_property = (TextView) v.findViewById(R.id.goods_property);
            goods_img = (ImageView) v.findViewById(R.id.goods_item_img);
            goods_feature = (TextView) v.findViewById(R.id.goods_feature);

            // 为每一个货物item的选择图片按钮设置tag，为的是选择图片之后确定放在哪个水平滑动里面。
            bill_select_bt = (ImageView) v.findViewById(R.id.result_select_img);
            bill_camera_bt = (ImageView) v.findViewById(R.id.result_camera);
            place_select_bt = (ImageView) v
                    .findViewById(R.id.result_select_img2);
            place_camera_bt = (ImageView) v.findViewById(R.id.result_camera2);
            fill_bt = (ImageView) v.findViewById(R.id.goods_select_file);

            bill_select_bt.setTag(i);
            bill_camera_bt.setTag(i);
            place_select_bt.setTag(i);
            place_camera_bt.setTag(i);
            fill_bt.setTag(i);

            goods_name.setText(data.goodsname);
            goods_property.setText(data.sizedesc);
            goods_count.setText(data.qty);
            goods_feature.setText(data.unitname);
            MyApplication.imageLoader.displayImage(NetManager.getDownloadURL() + "?filepath=" + data.simplepicfile, goods_img,
                    MyApplication.options);
            v.setTag(i);
            ll_goods_contener.addView(v);
        }
    }


    /*
     * 组建上传到服务器的json对象
     */
    private void buildJson() {
        try {
            if (allBillUploadFn && allPlaceUploadFn && allFileUploadFn) {
                JSONArray jsonArrALL = new JSONArray();
                //整体测量图片
                for (String str : allBillPaths) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("measureid", measureid);
                    jsonObj.put("imgpath", str);
                    jsonObj.put("type", "1");
                    jsonArrALL.put(jsonObj);
                }
                //整体现场图及整改图
                for (String str : allPlacePaths) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("measureid", measureid);
                    jsonObj.put("imgpath", str);
                    jsonObj.put("type", "2");
                    jsonArrALL.put(jsonObj);
                }
                saveParams.addBodyParameter("imgitem", jsonArrALL.toString());
                JSONArray jsonFileArr = new JSONArray();
                for (FileUploadBean allFile : allFileBeans) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("title", allFile.getTitle());
                    jsonObj.put("filepath", allFile.getFilepath());
                    jsonObj.put("filesize", allFile.getFilesize());
                    jsonFileArr.put(jsonObj);
                }
                saveParams.addBodyParameter("attachment", jsonFileArr.toString());
                //明细商品上的图片
                JSONArray jsonItemArr = new JSONArray();
                for (int i = 0; i < itemBill.size(); i++) {
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("measureitemid",
                            bean.data.measureitem.get(i).measureitemid);

                    JSONArray itemArrImg = new JSONArray();
                    for (int a = 0; a < itemBill.get(i).size(); a++) {
                        JSONObject jsonImgObj = new JSONObject();
                        jsonImgObj.put("path", itemBill.get(i).get(a));
                        jsonImgObj.put("name", "照片");
                        jsonImgObj.put("type", "1");
                        itemArrImg.put(jsonImgObj);
                    }
                    for (int b = 0; b < itemPlace.get(i).size(); b++) {
                        JSONObject jsonImgObj = new JSONObject();
                        jsonImgObj.put("path", itemPlace.get(i).get(b));
                        jsonImgObj.put("name", "现场整改照片");
                        jsonImgObj.put("type", "2");
                        itemArrImg.put(jsonImgObj);
                    }
                    for (int c = 0; c < itemFile.get(i).size(); c++) {
                        JSONObject jsonImgObj = new JSONObject();
                        jsonImgObj.put("path", itemFile.get(i).get(c));
                        jsonImgObj.put("name", "现场测量规格描述");
                        jsonImgObj.put("type", "3");
                        itemArrImg.put(jsonImgObj);
                    }

                    jsonObj.put("measureitemimg", itemArrImg);
                    jsonItemArr.put(jsonObj);
                }
                // Log.i("JSON", "measureitemimg = " + jsonItemArr.toString());
                saveParams.addBodyParameter("measureitem", jsonItemArr.toString());
                UiUtils.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        connect(saveParams, NetManager.RESULT);
                    }
                }, 2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.show(this, "提交出错：" + e.getMessage(), 2000);
            closeLoadDialog();
        }
    }

    // 开始保存数据到服务器
    public void save(View view) {
        closeLoadDialog();
        String actmeasuredate = tv_actual_time.getText().toString();
        String ctsNeed = et_cts_need.getText().toString();
        if (TextUtils.isEmpty(actmeasuredate)) {
            Toast.show(this, "请选择实际上门时间", 2000);
            return;
        }
        String prjcontactdate = tv_conversation_time.getText().toString();
        String predesignenddate = tv_finish_date.getText().toString();

        if (TextUtils.isEmpty(prjcontactdate)) {
            Toast.show(this, "请选择设计可完成时间", 2000);
            return;
        }
        if (TextUtils.isEmpty(actmeasuredate)) {
            Toast.show(this, "请选择方案交接时间", 2000);
            return;
        }
//        if (TextUtils.isEmpty(ctsNeed)) {
//            Toast.show(this, "请先输入客户需求", 2000);
//            return;
//        }

        saveParams = new RequestParams();
        saveParams.addBodyParameter("sf_action", "finish");
        saveParams.addBodyParameter("usercode", MyApplication.getUserCode());
        saveParams.addBodyParameter("measureid", measureid);
        saveParams.addBodyParameter("actmeasuredate", actmeasuredate);
        saveParams.addBodyParameter("actdemand", ctsNeed==null? "" : ctsNeed);
        saveParams.addBodyParameter("predesignenddate", predesignenddate);
        saveParams.addBodyParameter("prjcontactdate", prjcontactdate);
        saveParams.addBodyParameter("remark", "");
        //先上传图片
        initUpload();
        // 上传整体测试图片
        view_all_bill.postPics();
        // 上传现场整改图片
        view_all_place.postPics();
        //上传附件
        view_all_file.postFile();
    }

    private void initUpload() {
        showDialog("提交数据中...", false);
        if (allBillPaths == null) allBillPaths = new ArrayList<>();
        else allBillPaths.clear();
        allBillUploadFn = false;
        if (allPlacePaths == null) allPlacePaths = new ArrayList<>();
        else allPlacePaths.clear();
        allPlaceUploadFn = false;
        if (allFileBeans == null) allFileBeans = new ArrayList<>();
        else allFileBeans.clear();
        allFileUploadFn = false;
    }


    // 显示时间选择器
    public void showPicker(View view) {
        if (view.getId() == R.id.showPicker1) {
            AppDialog.createPicker(this, tv_actual_time).show();
        } else if (view.getId() == R.id.design_finish_date_layout) {
            AppDialog.createPicker(this, tv_finish_date).show();
        } else if (view.getId() == R.id.actual_come_date) {
            AppDialog.createPicker(this, tv_conversation_time).show();
        }
    }

    private boolean isCameraPhotoAtItem, isSelectPhototAtItem, isBillPhototAtItem, isFileAtItem;

    // 打开相机-为产品明细Item拍照
    public void openCameraAtItem(View view) {
        showDialog("", false);
        if (isOutOfLimitAtItem(view)) {
            dimssDialog();
            return;
        }
        isCameraPhotoAtItem = true;
        if (view.getId() == R.id.result_camera || view.getId() == R.id.result_select_img) {
            isBillPhototAtItem = true;
        }
        closeLoadDialog(0);
        ImageUtils.picOpenCamera(mActivity, (Integer) (view.getTag()));
    }

    // 打开图库-为产品明细Item选择照片
    public void selectPhotoAtItem(View view) {
        showDialog("", false);
        // 当达到最高图片数量时直接返回
        if (isOutOfLimitAtItem(view)) {
            dimssDialog();
            return;
        }
        isSelectPhototAtItem = true;
        if (view.getId() == R.id.result_camera || view.getId() == R.id.result_select_img) {
            isBillPhototAtItem = true;
        }
        List<LocalMedia> defaultLocalMedia = getLastList();
        closeLoadDialog(0);
        ImageUtils.picOpenGallery(mActivity, PictureConfig.MULTIPLE, (99 - currImgParentView.getChildCount()), defaultLocalMedia, (Integer) (view.getTag()));
    }

    /**
     * 判断容器里的图片是否达到最高选择数量
     */
    private ViewGroup currImgParentView;//当前图片的父容器中
    private List<LocalMedia> currImgList;//当前容器拥有的图片

    private boolean isOutOfLimitAtItem(View view) {
        currImgParentView = null;
        if (currImgList == null) currImgList = new ArrayList<>();
        else currImgList.clear();
        // 下面开始判断每个货物里的图片是否达到最高选择数量
        if (view.getId() == R.id.result_select_img || view.getId() == R.id.result_camera) {
            View item = (View) (view.getParent().getParent());
            ViewGroup group1 = (ViewGroup) item.findViewById(R.id.result_img_contener);
            if (group1.getChildCount() >= 99) {
                Toast.show(this, "当前选项测量单图片最多上传99张", 2000);
                return true;
            } else {
                currImgParentView = group1;
            }
        }
        if (view.getId() == R.id.result_select_img2 || view.getId() == R.id.result_camera2) {
            View item = (View) (view.getParent().getParent());
            ViewGroup group1 = (ViewGroup) item.findViewById(R.id.result_img_contener2);
            if (group1.getChildCount() >= 99) {
                Toast.show(this, "当前选项现场及整改图片最多上传99张", 2000);
                return true;
            } else {
                currImgParentView = group1;
            }
        }
        return false;
    }

    //获取上次选中的图片
    private List<LocalMedia> getLastList() {
        List<LocalMedia> lastList = new ArrayList<>();
        if (currImgParentView != null && currImgParentView.getChildCount() > 0) {
            for (int i = 0; i < currImgParentView.getChildCount(); i++) {
                String strUrl = "";
                try {
                    strUrl = (String) currImgParentView.getChildAt(i).getTag();
                    if (!TextUtils.isEmpty(strUrl) && goodsPhotoMap.containsKey(strUrl)) {
                        lastList.add(goodsPhotoMap.get(strUrl));
                    }
                } catch (Exception ee) {
                    ee.fillInStackTrace();
                }
            }
        }
        return lastList;
    }


    /**
     * 获取展示的图片，其中包含已上传和未上传的
     *
     * @param selectList
     * @param request
     */
    private List<BitmapItem> getShowImages(List<LocalMedia> selectList, int request) {
        List<BitmapItem> showImages = new ArrayList<>();

        LinearLayout goods = (LinearLayout) ll_goods_contener.getChildAt(request);
        if (null != goods) {
            if (isBillPhototAtItem) {
                for (LocalMedia localMedia : selectList) {
                    showImages.add(getBitmapItemByItemUploadedUrl(localMedia, null));
                }
            } else {
                for (LocalMedia localMedia : selectList) {
                    showImages.add(getBitmapItemByItemUploadedUrl(localMedia, null));
                }
            }
        }
        return showImages;
    }

    /**
     * 通过产品的已上传项设置当前显示的项
     *
     * @param localMedia
     * @param uploadedUrls
     * @return
     */
    private BitmapItem getBitmapItemByItemUploadedUrl(LocalMedia localMedia, ArrayList<ArrayList<String>> uploadedUrls) {
        BitmapItem bitmapItem = new BitmapItem();
        try {
            String path = localMedia.getCompressPath();
            if (TextUtils.isEmpty(path)) {
                path = localMedia.getPath();
            }
            bitmapItem.setLocaPath(path);
            if (uploadedUrls != null && uploadedUrls.size() > 0) {
                try {
                    String[] arr = path.split("/");
                    String pathCutPath = arr[arr.length-2] + "/" + arr[arr.length-1];//截取最后两截来判断
                    for (ArrayList<String> strList : uploadedUrls) {
                        boolean breakIn = false;
                        for (String url: strList) {
                            if (url.contains(pathCutPath)) {
                                bitmapItem.setUploadedPath(url);
                                breakIn = true;
                                break;
                            }
                        }
                        if (breakIn) {
                            break;
                        }
                    }
                }catch (Exception ee){}
            }
            goodsPhotoMap.put(path, localMedia);
        } catch (Exception ee) {
        }
        return bitmapItem;
    }

    // 选择文件
    public void selectFileAtItem(View view) {
        isFileAtItem = true;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, (Integer) (view.getTag()));// SELECT_FILE
    }

    // 删除显示在界面上的图片
    public void delete_img(View view) {
        View chil = (View) (view.getParent().getParent());
        ViewGroup parent = (ViewGroup) (view.getParent().getParent()
                .getParent());
        parent.removeView(chil);
        if (parent.getChildCount() < 1) {
            ((View) (parent.getParent())).setVisibility(View.GONE);
        }
        delete_img_local(view);
    }

    // 删除本地上传的图片
    private void delete_img_local(View view) {
        if (view.getTag() != null) {
            DeleteTag tag = (DeleteTag) view.getTag();
            // 再查找删除的图片是不是在对应条目的测量单里面
            if (tag.isBill) {
                ArrayList<String> child = itemBill.get(tag.position);
                for (int b = 0; b < child.size(); b++) {
                    if (tag.fileName.equals(FileUtil.getFileName(child.get(b)))) {
                        child.remove(b);
                        return;// 这里return是因为可能存在相同文件名的文件都会删除
                    }

                }
            }else if (tag.isPlace) {// 再查找删除的图片是不是在对应条目的现场整改里面
                ArrayList<String> child = itemPlace.get(tag.position);
                for (int b = 0; b < child.size(); b++) {
                    if (tag.fileName.equals(FileUtil.getFileName(child.get(b)))) {
                        child.remove(b);
                        return;// 这里return是因为可能存在相同文件名的文件都会删除
                    }
                }
            }
        }
    }

    // 先删除界面上在显示的图片
    public void deleteFile(View view) {
        RelativeLayout child = (RelativeLayout) (view.getParent().getParent());
        ViewGroup parent = (ViewGroup) (child.getParent());
        parent.removeView(child);
        if (parent.getChildCount() == 0) {
            parent.setVisibility(View.GONE);
        }
        delete_file_local(view);
    }

    // 再删除要上传到服务器的图片
    private void delete_file_local(View view) {
        if (view.getTag() != null) {
            DeleteTag tag = (DeleteTag) view.getTag();
            // 查找删除的图片是不是在整体现场整改里面
            if (tag.isFile) {
                ArrayList<String> child = itemFile.get(tag.position);
                for (int k = 0; k < child.size(); k++) {
                    if (tag.fileName.equals(FileUtil.getFileName(child.get(k)))) {
                        child.remove(k);
                        return;// 这里return是因为可能存在相同文件名的文件都会删除
                    }
                }
            }
        }
    }

    // 这些变量是用来检测所选择的图片或文件存放到对应的父容器里面
    private int INTO_ALL_BILL = 111, INTO_ALL_PLACE = 222, INTO_BILL = 8800,
            INTO_PLACE = 9900, INTO_FILE = 7700;

    private List<BitmapItem> mSelectPath;//本次需要上传的图片

    //打开图库
    @Override
    public void openAlbum(int id) {
        // 当达到最高图片数量时直接返回
        if (isOutOfLimitAtAll(id))
            return;
        List<LocalMedia> lastMedias = new ArrayList<>();
        if (id == CODE_ALL_BILL) {
            lastMedias.addAll(view_all_bill.getFileList());
        } else if (id == CODE_ALL_PLACE) {
            lastMedias.addAll(view_all_place.getFileList());
        }
        ImageUtils.pictureSelect(mActivity, PictureConfig.MULTIPLE, 99, lastMedias, id + 1);
    }

    //打开相机拍照
    @Override
    public boolean openCamera(int id) {
        // 当达到最高图片数量时直接返回
        return isOutOfLimitAtAll(id);
//        if (isOutOfLimitAtAll(id))
//            return;
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        startActivityForResult(intent, id + 2);
    }

    /**
     * 判断容器里的图片是否达到最高选择数量
     */
    private boolean isOutOfLimitAtAll(int code) {
        // 下面开始判断整体容器里的图片是否达到最高选择数量
        if (code == CODE_ALL_BILL) {
            if (view_all_bill.getPhotosCount() >= 99) {
                Toast.show(this, "整体测量单图片最多上传99张", 2000);
                return true;
            }
        } else if (code == CODE_ALL_PLACE) {
            if (view_all_place.getPhotosCount() >= 99) {
                Toast.show(this, "整体现场及整改图片最多上传99张", 2000);
                return true;
            }
        }
        return false;
    }

    @Override
    public void showLoadDialog() {
        showDialog("上传图片中...", false);
    }

    @Override
    public void closeLoadDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    //上传单张图片
    @Override
    public void uploadPic(RequestParams params, int requestCode) {
        updateIMG(params, requestCode);
    }


    @Override
    public void uploadVideoByParam(RequestParams params, int code) {
        uploadVideo(params, code);
    }

    @Override
    public void afterUploadVideos(boolean isSuccess, ArrayList<BeanImage> urls, int requestCode) {

    }

    @Override
    public void uploadFile(RequestParams params, int requestCode) {
        updateIMG(params, requestCode);
    }

    //所有图片上传成功
    @Override
    public void afterUploadPics(boolean isSuccess, ArrayList<String> urls, int _id) {
        if (isSuccess) {
            if (_id == CODE_ALL_BILL) {
                allBillUploadFn = true;
                allBillPaths = urls;
            } else if (_id == CODE_ALL_PLACE){
                allPlaceUploadFn = true;
                allPlacePaths = urls;
            }
            buildJson();
        }else {
            closeLoadDialog();
        }
    }


    @Override
    public void afterUploadFile(ArrayList<FileUploadBean> fileUploadBeans, int requestCode) {
        if (requestCode == CODE_ALL_FILE) {
            allFileUploadFn = true;
            allFileBeans = fileUploadBeans;
        }
        buildJson();
    }


    class DeleteTag {
        public boolean isBill;
        public boolean isPlace;
        public boolean isFile;

        public int position;
        public String fileName;
    }

    @Override
    protected void onActivityResult(final int request, int result, Intent data) {
        super.onActivityResult(request, result, data);
        if (result != RESULT_OK) {
            return;
        }
        if (Math.abs(request - CODE_ALL_BILL) < 4) {//整体测量单照片
            view_all_bill.onActivityResult(request, data);
        }else if (Math.abs(request - CODE_ALL_PLACE) < 4){//整体现场及整改图片
            view_all_place.onActivityResult(request, data);
        }else if (request == CODE_ALL_FILE  && data != null) {//整体附件选择
            view_all_file.updateFilesRecyclerView(mActivity, data);
        }else if (isCameraPhotoAtItem && data != null) {// 当图片是由照相机拍摄时
            isCameraPhotoAtItem = false;
            List<LocalMedia> photos = PictureSelector.obtainMultipleResult(data);
            if (photos != null && photos.size() > 0) {
                final LocalMedia addLocalMedia = photos.get(0);
                try {
                    if (TextUtils.isEmpty(addLocalMedia.getCompressPath())) {
                        PictureUtil.compressImage(mActivity, addLocalMedia.getCompressPath(), 60, new PictureUtil.Compress() {
                            @Override
                            public void done(String compressPath, String fileName) {
                                afterPhotograph(compressPath, fileName, request, addLocalMedia);
                            }

                        });
                    } else {
                        afterPhotograph(addLocalMedia.getCompressPath(), FileUtil.getFileName(addLocalMedia.getCompressPath()), request, addLocalMedia);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else if (isSelectPhototAtItem) {// 当图片是从图库里选择时
            isSelectPhototAtItem = false;
            afterSleectPhoto(data, request);
        } else if (isFileAtItem) { // 从sd卡选择了文件
            Uri uri = data.getData();
            String file_path = FileUtils.getPath(this, uri);
            if (!TextUtils.isEmpty(file_path)) {
                String name = FileUtil.getFileName(file_path);
                RelativeLayout rl = (RelativeLayout) View.inflate(this,
                        R.layout.other_item, null);
                RelativeLayout rl2 = (RelativeLayout) rl.getChildAt(0);
                TextView tv = (TextView) rl2.getChildAt(0);
                tv.setText(name);
                rl.setTag(file_path);

                View delete = rl.findViewById(R.id.item_deleteFile);
                DeleteTag tag = new DeleteTag();
                tag.fileName = name;
                delete.setTag(tag);

                showDialog("上文件中...", false);
                closeLoadDialog(1500);

                RequestParams forFile = new RequestParams();
                forFile.addBodyParameter("usercode",
                        MyApplication.getUserCode());
                forFile.addBodyParameter("dir", "file");
                forFile.addBodyParameter("imgFile", new File(file_path));

                LinearLayout item = (LinearLayout) ll_goods_contener
                        .getChildAt(request);
                LinearLayout filContener = (LinearLayout) item
                        .findViewById(R.id.result_file_contener);
                filContener.addView(rl);
                updateIMG(forFile, INTO_FILE + request);
                tag.isFile = true;
                tag.position = request;
            } else {
                file_path = PictureFileUtils.getPath(MeasureInputActivity.this,data.getData());// FileUtil.getFileRealPath(MeasureInputActivity.this,data);
                if (TextUtils.isEmpty(file_path)) {
                    Toast.show(this, "不支持的文件类型", 2000);
                } else {
                    String name = FileUtil.getFileName(file_path);
                    RelativeLayout rl = (RelativeLayout) View.inflate(this,
                            R.layout.other_item, null);
                    RelativeLayout rl2 = (RelativeLayout) rl.getChildAt(0);
                    TextView tv = (TextView) rl2.getChildAt(0);
                    tv.setText(name);
                    rl.setTag(file_path);

                    View delete = rl.findViewById(R.id.item_deleteFile);
                    DeleteTag tag = new DeleteTag();
                    tag.fileName = name;
                    delete.setTag(tag);
                    // file_contener.addView(rl);RequestParams forIMG = new
                    // RequestParams();
                    RequestParams forFile = new RequestParams();
                    forFile.addBodyParameter("usercode",
                            MyApplication.getUserCode());
                    forFile.addBodyParameter("dir", "file");
                    File file = new File(file_path);
                    forFile.addBodyParameter("imgFile", file);

                    LinearLayout item = (LinearLayout) ll_goods_contener
                            .getChildAt(request);
                    LinearLayout filContener = (LinearLayout) item
                            .findViewById(R.id.result_file_contener);
                    filContener.addView(rl);
                    updateIMG(forFile, INTO_FILE + request);
                    tag.isFile = true;
                    tag.position = request;
                }
            }
            isFileAtItem = false;
        }
        setContenerVisible();
    }

    //拍照后上传图片
    private void afterPhotograph(String compressPath, String fileName, int request, LocalMedia addLocalMedia) {
        // 上传图片
        View view = View.inflate(mActivity, R.layout.img_item, null);
        ImageView src = (ImageView) view.findViewById(R.id.item_img);
        if (!TextUtils.isEmpty(compressPath)) {
            goodsPhotoMap.put(compressPath, addLocalMedia);
            view.setTag(compressPath);
            // 只为删除图片时将集合里的数据清除
            View delete = view.findViewById(R.id.img_delete);
            DeleteTag tag = new DeleteTag();
            tag.fileName = fileName;
            delete.setTag(tag);
            BitmapHelper.displayImg(compressPath, src, false);
            src.setTag(compressPath);
            showDialog("上传图片中...", false);
            closeLoadDialog(1500);
            RequestParams forIMG = new RequestParams();
            forIMG.addBodyParameter("usercode", MyApplication.getUserCode());
            forIMG.addBodyParameter("dir", "image");
            forIMG.addBodyParameter("imgFile", new File(compressPath));
            LinearLayout goods = (LinearLayout) ll_goods_contener
                    .getChildAt(request);
            tag.position = request;// 删除第几个货物的图片
            if (null != goods) {
                LinearLayout contener;
                if (isBillPhototAtItem) {
                    contener = (LinearLayout) goods
                            .findViewById(R.id.result_img_contener);
                    contener.addView(view);
                    isBillPhototAtItem = false;
                    updateIMG(forIMG, INTO_BILL + request);// 加上request说明是第几个item的图片
                    tag.isBill = true;
                } else {
                    contener = (LinearLayout) goods
                            .findViewById(R.id.result_img_contener2);
                    contener.addView(view);
                    updateIMG(forIMG, INTO_PLACE + request);// 加上request说明是第几个item的图片
                    tag.isPlace = true;
                }
            }
        } else {
            src.setTag("");
        }
    }

    //选择照片后上传
    private void afterSleectPhoto(Intent data, int request) {
        List<LocalMedia> photos = PictureSelector.obtainMultipleResult(data);
        if (photos.size() > 0) {
            showDialog("上传图片中...", false);
            mSelectPath = getShowImages(photos, request);
            if (mSelectPath.size() > 0) {// 做延迟图片处理
                closeLoadDialog(mSelectPath.size() * 1500);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    BitmapItem bItem = mSelectPath.get(i);
                    View view = View.inflate(this, R.layout.img_item, null);
                    view.setTag(bItem.getLocaPath());
                    // 只为删除图片时将集合里的数据清除
                    View delete = view.findViewById(R.id.img_delete);
                    DeleteTag tag = new DeleteTag();
                    tag.fileName = FileUtil.getFileName(bItem.getLocaPath());
                    delete.setTag(tag);
                    ImageView src = (ImageView) view.findViewById(R.id.item_img);
                    BitmapHelper.displayImg(bItem.getLocaPath(), src, false);
                    // src.setImageBitmap(photo);
                    src.setTag(bItem.getLocaPath());
                    LinearLayout goods = (LinearLayout) ll_goods_contener.getChildAt(request);
                    tag.position = request;// 删除第几个货物的图片
                    if (null != goods) {
                        LinearLayout contener;
                        if (isBillPhototAtItem) {
                            contener = (LinearLayout) goods.findViewById(R.id.result_img_contener);
                            if (i == 0) {
                                contener.removeAllViews();
                            }
                            contener.addView(view);
                            tag.isBill = true;
                            if (bItem.getUploadedPath().equals("")) {//上传的图片
                                RequestParams forIMG = new RequestParams();
                                forIMG.addBodyParameter("usercode", MyApplication.getUserCode());
                                forIMG.addBodyParameter("dir", "image");
                                forIMG.addBodyParameter("imgFile", new File(bItem.getLocaPath()));
                                updateIMG(forIMG, INTO_BILL + request);
                            }
                        } else {
                            contener = (LinearLayout) goods.findViewById(R.id.result_img_contener2);
                            if (i == 0) {
                                contener.removeAllViews();
                            }
                            contener.addView(view);
                            tag.isPlace = true;
                            if (bItem.getUploadedPath().equals("")) {//上传的图片
                                RequestParams forIMG = new RequestParams();
                                forIMG.addBodyParameter("usercode", MyApplication.getUserCode());
                                forIMG.addBodyParameter("dir", "image");
                                forIMG.addBodyParameter("imgFile", new File(bItem.getLocaPath()));
                                updateIMG(forIMG, INTO_PLACE + request);
                            }
                        }
                    }
                }
            } else closeLoadDialog(0);
        }
        isBillPhototAtItem = false;
    }

    // 当某个图片的父容器有图片时就需要将它设置为可见
    public void setContenerVisible() {
        for (int i = 0; i < ll_goods_contener.getChildCount(); i++) {
            LinearLayout item = (LinearLayout) ll_goods_contener.getChildAt(i);

            ViewGroup scroller1 = (ViewGroup) item
                    .findViewById(R.id.reult_scrollview);
            LinearLayout group1 = (LinearLayout) scroller1.getChildAt(0);
            if (!(scroller1.getVisibility() == View.VISIBLE)
                    && group1.getChildCount() > 0) {
                scroller1.setVisibility(View.VISIBLE);
            }

            ViewGroup scroller2 = (ViewGroup) item
                    .findViewById(R.id.reult_scrollview2);
            LinearLayout group2 = (LinearLayout) scroller2.getChildAt(0);
            if (!(scroller2.getVisibility() == View.VISIBLE)
                    && group2.getChildCount() > 0) {
                scroller2.setVisibility(View.VISIBLE);
            }

            LinearLayout filContener = (LinearLayout) item
                    .findViewById(R.id.result_file_contener);
            if (!(filContener.getVisibility() == View.VISIBLE)
                    && filContener.getChildCount() > 0) {
                filContener.setVisibility(View.VISIBLE);
            }
        }
    }

    // 看大图
    public void viewPhoto(View view) {
        viewGoods(view);
    }

    public void getDesignBill(View view) {
        RelativeLayout rl = (RelativeLayout) view;
        CheckBox rb = (CheckBox) rl.getChildAt(1);
        if (rb.isChecked()) {
            rb.setChecked(false);
            // valueAnim(list_contener.getMeasuredHeight(),0, list_contener);
            ll_list_contener.setVisibility(View.GONE);
        } else {
            rb.setChecked(true);
            // valueAnim(0,list_contener.getMeasuredHeight(), list_contener);
            ll_list_contener.setVisibility(View.VISIBLE);
        }
    }

    public void viewGoods(View view) {
        showGoodsPop(view.getTag().toString());
    }

    private PopupWindow sharedPop;

    // 看大图
    public void showGoodsPop(String url) {
        if (sharedPop == null) {
            View contentView = View.inflate(this, R.layout.shared_pop_window,
                    null);
            sharedPop = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT, true);
            sharedPop.setAnimationStyle(R.style.goods_pop);
            sharedPop.setBackgroundDrawable(new BitmapDrawable());
            sharedPop.setFocusable(true);
        }
        ImageView iv = (ImageView) sharedPop.getContentView().findViewById(
                R.id.goods_img_big);
        iv.setImageBitmap(BitmapFactory.decodeFile(url));
        // MyApplication.imageLoader.displayImage(url, iv);
        sharedPop.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }

    public void closeGoodsPop(View view) {
        sharedPop.dismiss();
    }

    @Override
    public void onBackPressed() {
        if (null != sharedPop && sharedPop.isShowing()) {
            sharedPop.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (sharedPop != null && sharedPop.isShowing()) {
            sharedPop.dismiss();
        }
        if (goodsPhotoMap != null) goodsPhotoMap.clear();
        saveParams = null;
        super.onDestroy();
    }

    private void closeLoadDialog(int time) {
        UiUtils.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }
        }, time);
    }
}
